package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.simple.AbstractSimpleElasticJob;
import com.lsh.base.trace.id.filter.TraceIdSetter;
import com.lsh.ofc.api.dto.SoHeadDTO;
import com.lsh.oms.core.enums.TaskStatus;
import com.lsh.oms.core.enums.TaskType;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.order.OrderSignDetail;
import com.lsh.oms.core.model.order.OrderSignHead;
import com.lsh.oms.core.model.po.OmsTask;
import com.lsh.oms.core.proxy.handler.OrderConcurrentHandler;
import com.lsh.oms.core.proxy.service.OfcProxy;
import com.lsh.oms.core.proxy.service.WgServiceProxy;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.other.SignOrderService;
import com.lsh.oms.core.service.po.OmsTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * Project Name: FillOrderDetailTask
 * 北京链商电子商务有限公司
 * Auth: peter
 * Date: 19/4/18
 * Package Name: com.lsh.oms.worker.service.task
 * Description:
 */
@Component
public class OrderPoSoToPsiTask extends AbstractSimpleElasticJob {
    private static final Logger logger = LoggerFactory.getLogger(OrderPoSoToPsiTask.class);

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private SignOrderService signOrderService;

    @Autowired
    private OfcProxy ofcProxy;

    @Autowired
    private WgServiceProxy wgServiceProxy;

    @Autowired
    private OmsTaskService omsTaskService;

    @Value("${mis.host}")
    private String misUrl;

    @Value("${shopUrl}")
    private String shopUrl;

    protected Integer process(OmsTask omsTask) {
        TraceIdSetter.set();
        if (omsTask == null) {
            return -1;
        }

        Long orderCode = Long.valueOf(omsTask.getRefCode());
        String logSign = "【" + orderCode + " - po so psi】";
        try {
            if (!OrderConcurrentHandler.lockOrder(orderCode)) {
                logger.info("{}processData({}) interrupt... 订单正在处理...", logSign, orderCode);
                return -1;
            }

            OrderHead orderHead = orderQueryService.findByCode(orderCode, false, true);
            if (orderHead == null || CollectionUtils.isEmpty(orderHead.getDetails())) {
                logger.info("{}查询不到订单 或 订单详情，订单号：{}", logSign, orderCode);
                return -1;
            }

            JSONObject orderExt = JSON.parseObject(orderHead.getExt());
            String providerId = orderExt.getString("providerId");

            OrderSignHead signHead = signOrderService.getSignHeadByOrderId(orderCode,false);
            if (signHead == null) {
                logger.info("can not find sign order by {}", orderCode);
                return 0;
            }
            List<OrderSignDetail> orderSignDetails = signOrderService.selectByReceiptOrderId(signHead.getReceiptOrderId());

            if (CollectionUtils.isEmpty(orderSignDetails)) {
                logger.info("can not find sign order items by {}", signHead.getReceiptOrderId());
                return 0;
            }

            List<SoHeadDTO> soHeadDTOList = ofcProxy.getSoInfo(orderCode);
            if (CollectionUtils.isEmpty(soHeadDTOList)) {
                logger.info("can not find so by {}", orderCode);
                return -1;
            }
            SoHeadDTO soHeadDTO = soHeadDTOList.get(0);
            JSONObject contentJson = new JSONObject();
            contentJson.put("order_id", soHeadDTO.getSoBillCode());
            contentJson.put("warehouse_code", soHeadDTO.getWarehouseCode());
            contentJson.put("warehouse_order_no", soHeadDTO.getSoBillCode());
            contentJson.put("owner_id", "1");
            contentJson.put("vender_id", providerId);
            contentJson.put("receive_date", signHead.getReceiptAt().toString());

            JSONArray goodsList = new JSONArray();

            JSONObject detail;
            for (OrderSignDetail signDetail : orderSignDetails) {
                detail = new JSONObject();
                JSONObject extJson = JSON.parseObject(signDetail.getExt());

                detail.put("line_no", signDetail.getItemCode());
                detail.put("goods_id", extJson.getString("wm_code"));
                detail.put("qty", signDetail.getRealQty());
                goodsList.add(detail);
            }
            contentJson.put("goods_list", goodsList);
            return wgServiceProxy.pushPoSo(contentJson, orderHead.getVenderId());
        } catch (Exception e) {
            logger.error(logSign + "任务处理异常", e);
        } finally {
            OrderConcurrentHandler.unlockOrder(orderCode);
        }

        return -1;
    }

    @Override
    public void process(JobExecutionMultipleShardingContext context) {
//        if (map == null || map.isEmpty()) {
//            logger.info("【填充订单详情税率】任务参数为空!");
//            return;
//        }

        List<OmsTask> omsTaskList = this.omsTaskService.getTasksByTypeAndStatuses(this.getTaskType().getCode(), this.dealTaskStatus(), this.getFetchSize());
        logger.info("【填充订单详情税率】任务size:【{}】", omsTaskList.size());

        for (OmsTask omsTask : omsTaskList) {
            try {
                Integer processFlag = this.process(omsTask);

                if (processFlag == 0) {
                    continue;
                }

                //更新数据库
                OmsTask task4Update = new OmsTask();
                task4Update.setId(omsTask.getId());
                task4Update.setExecCount(omsTask.getExecCount() + 1);
                Integer taskStatus = TaskStatus.TASK_DEAL_SUCCESS.getCode();
                if (processFlag == -1) {
                    taskStatus = TaskStatus.TASK_DEAL_FAIL.getCode();
                }
                task4Update.setTaskStatus(taskStatus);
                this.omsTaskService.update(task4Update);
            } catch (Exception e) {
                logger.error("【填充订单详情税率】系统异常", e);
            }
        }

    }


    private Integer getFetchSize() {
        return 100;
    }

    private TaskType getTaskType() {
        return TaskType.ORDER_REICEPT_PO_SO_PSI;
    }

    private List<Integer> dealTaskStatus() {
        return Arrays.asList(TaskStatus.TASK_UN_DEAL.getCode(), TaskStatus.TASK_DEAL_FAIL.getCode());
    }
}
